import { getApiAreasRegeo } from "@/model/index"

const net_work = async () => {
  return new Promise((resolve: any) => {
    uni.getNetworkType({
      success(res) {
        if (res.networkType == 'wifi') {
          uni.startWifi({
            success(res) { },
            fail: function (res) { }
          })
          uni.getConnectedWifi({
            success(e) {
              return resolve({ ...res, ...e.wifi })
            },
            fail(err) {
              resolve({ ...res, remark: err })
            }
          })
        } else {
          resolve({ ...res })
        }


      },
      fail() {
        resolve()
      }
    })
  })
}


// ip
// const ip_address = new Promise((resolve: any) => {
//   uni.getLocalIPAddress({
//     success(res) {
//       resolve(res)

//     },
//     fail() {
//       resolve()
//     }
//   })
// })

const getNetworkInfo = async () => {
  return new Promise((resolve: any) => {
    uni.getNetworkType({
      success(res) {
        console.log('networkinfo -----', res)
        return resolve(res)
      },
      fail: () => {
        return resolve({ msg: '获取网络失败' })
      }
    })
  })
};
const getLocation = async () => {
  return new Promise((resolve: any) => {
    uni.getLocation({
      success(res) {
        console.log('location info -----', res)
        return resolve(res)
      },
      fail: () => {
        return resolve({ msg: '获取定位失败' })
      }
    })
  })
};
function judgeBrand(sUserAgent: any) {
  var isIphone = sUserAgent.match(/iphone/i) == "iphone";
  var isHuawei = sUserAgent.match(/huawei/i) == "huawei";
  var isHonor = sUserAgent.match(/honor/i) == "honor";
  var isOppo = sUserAgent.match(/oppo/i) == "oppo";
  var isOppoR15 = sUserAgent.match(/pacm00/i) == "pacm00";
  var isVivo = sUserAgent.match(/vivo/i) == "vivo";
  var isXiaomi = sUserAgent.match(/mi\s/i) == "mi ";
  var isXiaomi2s = sUserAgent.match(/mix\s/i) == "mix ";
  var isRedmi = sUserAgent.match(/redmi/i) == "redmi";
  var isSamsung = sUserAgent.match(/sm-/i) == "sm-";

  if (isIphone) {
    return 'iphone';
  } else if (isHuawei || isHonor) {
    return 'huawei';
  } else if (isOppo || isOppoR15) {
    return 'oppo';
  } else if (isVivo) {
    return 'vivo';
  } else if (isXiaomi || isRedmi || isXiaomi2s) {
    return 'xiaomi';
  } else if (isSamsung) {
    return 'samsung';
  } else {
    return 'unknown';
  }
}


export async function getMoreInfo() {


  let obj: any = {}
  return Promise.all([await net_work()]).then(async (res: any) => {
    // 设备信息
    const info = uni.getSystemInfoSync()

    // 内存大小
    const device: any = uni.getDeviceInfo()

    // #ifdef MP-WEIXIN

    // 小程序版本
    const account = uni.getAccountInfoSync();
    // #endif
    // 电量
    const getbattery = () => {
      Promise.resolve(() => {
        uni.getBatteryInfo({
          success: (res) => {
            return Promise.resolve(res)
          },
          fail: () => {
            return Promise.resolve({ msg: '获取电量失败' })
          }
        })
      })
    }
    const battery: any = await getbattery()

    const networkInfo: any = await getNetworkInfo()
    let location: any = await getLocation()
    location = location ?? {}


    console.log('信息', res, battery, location);
    obj = {
      device_id: device.deviceId,
      device_type: device.deviceType || info.deviceType,
      device_brand: device.deviceBrand || info.deviceBrand,
      device_model: device.deviceModel,
      device_orientation: device.deviceOrientation,
      device_pixel_ratio: device.devicePixelRatio,

      os_name: info.osName,
      os_version: info.osVersion,
      os_language: info.osLanguage,
      os_theme: info.osTheme,
      os_android_api_level: info && info.osAndroidAPILevel,
      rom_name: info.romName,
      rom_version: info.romVersion,
      browser_name: info.browserName,
      browser_version: info.browserVersion,
      host_name: info.hostName,
      host_version: info.hostVersion,
      host_language: info.hostLanguage,
      host_theme: info && info.hostTheme,
      host_font_size_setting: info.hostFontSizeSetting,
      host_package_name: info.hostPackageName,
      host_sdk_version: info.hostSDKVersion,

      uni_platform: info.uniPlatform,
      uni_compile_version: info.uniCompileVersion,
      uni_runtime_version: info.uniRuntimeVersion,

      app_id: info.appId,
      app_name: info.appName,
      app_version: info.appVersion,
      app_version_sdk: info.SDKVersion,
      app_version_code: info.appVersionCode,
      app_wgt_version: info.appWgtVersion,
      app_language: info.appLanguage,

      system_ua: info.ua,
      system_screen_width: info.screenWidth,
      system_screen_height: info.screenHeight,
      system_window_width: info.windowWidth,
      system_window_height: info.windowHeight,
      system_window_top: info.windowTop,
      system_window_bottom: info.windowBottom,
      system_status_bar_height: info.statusBarHeight,
      system_safe_area: info.safeArea,
      system_safe_area_insets: info.safeAreaInsets,

      tencent_enchmark_level: info.benchmarkLevel,
      tencent_battery_level: info.batteryLevel,
      tencent_navigation_bar_height: info.navigationBarHeight,
      tencent_title_bar_height: info.titleBarHeight,
      tencent_album_authorized: info.albumAuthorized,
      tencent_camera_authorized: info.cameraAuthorized,
      tencent_location_authorized: info.locationAuthorized,
      tencent_notification_authorized: info.notificationAuthorized,
      tencent_notification_alert_authorized: info.notificationAlertAuthorized,
      tencent_notification_badge_authorized: info.notificationBadgeAuthorized,
      tencent_notification_sound_authorized: info.notificationSoundAuthorized,
      tencent_bluetooth_enabled: info.bluetoothEnabled,
      tencent_location_enabled: info.locationEnabled,
      tencent_wifi_enabled: info.wifiEnabled,
      tecent_wifi_name: info.wifiName || res[0].wifiName,
      baidu_cache_location: info.cacheLocation,
      baidu_navigation_bar_height: info.navigationBarHeight,
      alipay_storage: info.storage,
      alipay_current_battery: info.currentBattery,

      network_type: networkInfo && networkInfo.networkType || res[0].networkType,

      location_latitude: location.latitude,
      location_longitude: location.longitude,
      location_speed: location.speed,
      location_accuracy: location.accuracy,
      location_alititude: location.alititude,
      location_verticalAccuracy: location.verticalAccuracy,
      location_horizontalAccuracy: location.horizontalAccuracy,
      address_text: location.address,
      address_country: location.country,
      address_province: location.province,
      address_city: location.city,
      address_district: location.district,
      address_street: location.street,
      address_street_num: location.streetNum,
      address_poi_name: location.poiName,
      address_postal_code: location.postalCode,
      address_city_code: location.cityCode,


      tripartite_type: 'LOGIN',
      tripartite_id: '',
      remark: res[0].remark || '',
      // network_type: res[0].networkType,

      network_signal_strength: res[0].signalStrength,
      network_has_system_proxy_flg: res[0].hasSystemProxy,
      window_screen_width: info.screenWidth,
      window_screen_height: info.screenHeight,
      window_width: info.windowWidth,
      window_height: info.windowHeight,
      window_screen_top: info.statusBarHeight,
      // system_status_bar_height: info.statusBarHeight,
      window_pixel_ratio: info.pixelRatio,
      system_bluetooth_enabled: info.bluetoothEnabled ? 1 : 0,
      system_location_enabled: info.locationEnabled ? 1 : 0,
      system_device_orientation: info.deviceOrientation,
      system_version: info.system,
      system_weixin_version: info.version,
      // #ifdef MP-WEIXIN
      // network_netmask: res[1].netmask,
      // network_local_ip: res[1].localip,
      system_app_env: account.miniProgram.envVersion,
      system_app_version: account.miniProgram.version,
      // #endif

      system_brand: info.brand,
      system_model: info.model,
      system_language: info.language,
      system_font_size_setting: info.fontSizeSetting,
      system_sdk_version: info.SDKVersion,
      system_benchmark_level: info.benchmarkLevel,
      system_album_authorized: info.albumAuthorized ? 1 : 0,
      system_camera_authorized: info.cameraAuthorized ? 1 : 0,
      system_microphone_authorized: info.microphoneAuthorized ? 1 : 0,
      system_notification_authorized: info.notificationAuthorized ? 1 : 0,
      system_notification_alert_authorized: info.notificationAlertAuthorized ? 1 : 0,
      system_notification_badge_authorized: info.notificationBadgeAuthorized ? 1 : 0,
      system_notification_sound_authorized: info.notificationSoundAuthorized ? 1 : 0,
      system_phone_calendar_authorized: info.phoneCalendarAuthorized ? 1 : 0,
      system_wifi_enabled: info.wifiEnabled ? 1 : 0,
      system_wifi_ssid: res[0].SSID,
      system_wifi_bssid: res[0].BSSID,
      system_wifi_secure: res[0].secure,
      system_wifi_signal_strength: res[0].signalStrength,
      system_theme: info.theme,
      system_enable_debug: info.enableDebug ? 1 : 0,
      system_cpu_type: device.cpuType,
      system_memory_size: device.memorySize,
      system_battery_level: battery && battery.level,
      system_battery_charging: battery && battery.isCharging
    }
    if (location.latitude) {
      try {
        const { address } = await getApiAreasRegeo({ location: `${location.longitude},${location.latitude}` }, { noCache: true })
        obj.address_text = address.formatted_address
        obj.address_country = address.addressComponent.country
        obj.address_province = address.addressComponent.province
        obj.address_city = address.addressComponent.city
        obj.address_district = address.addressComponent.district
      } catch (error) {
      }


    }
    // #ifdef H5
    if (!obj.device_brand || obj.device_brand == 'unknown') {
      obj.device_brand = judgeBrand(navigator.userAgent.toLowerCase());
    }
    if (!obj.network_type || obj.network_type == 'unknown') {
      var ua = navigator.userAgent;
      var networkStr = ua.match(/NetType\/\w+/) ? ua.match(/NetType\/\w+/)[0] : 'NetType/other';
      networkStr = networkStr.toLowerCase().replace('nettype/', '');
      var networkType;
      switch (networkStr) {
        case 'wifi':
          networkType = 'wifi';
          break;
        case '4g':
          networkType = '4g';
          break;
        case '3g':
          networkType = '3g';
          break;
        case '3gnet':
          networkType = '3g';
          break;
        case '2g':
          networkType = '2g';
          break;
        default:
          networkType = 'unknown';
      }
      obj.network_type = networkType
    }
    // #endif
    return Promise.resolve(obj)
  })
}